import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../common/routes.dart';
import '../common/utils.dart';
import '../model/category_item.dart';

class CategoryListView extends StatefulWidget {
  const CategoryListView({super.key});

  @override
  State<CategoryListView> createState() => _CategoryListViewState();
}

class _CategoryListViewState extends State<CategoryListView> with AutomaticKeepAliveClientMixin {
  final List<CategoryItem> categories = [];
  bool _isLoadingData = true;

  @override
  void initState() {
    super.initState();

    _loadData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  _loadData() async {
    Dio dio = Dio();
    final url = "https://baobab.kaiyanapp.com/api/v4/categories";
    final response = await dio.get(url);
    var list = (response.data as List<dynamic>).map((e) => CategoryItem.fromJson(e as Map<String, dynamic>)).toList();
    setState(() {
      _isLoadingData = false;
      categories.addAll(list);
    });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (_isLoadingData) {
      return Center(
        child: Container(
          margin: const EdgeInsets.all(8.0),
          width: 64.0,
          height: 64.0,
          child: const CircularProgressIndicator(),
        ),
      );
    }
    return GridView.builder(
      shrinkWrap: true,
      padding: const EdgeInsets.all(6),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 6,
        mainAxisSpacing: 6,
      ),
      itemCount: categories.length,
      itemBuilder: (context, index) {
        var imageUrl = categories[index].bgPicture;
        imageUrl = convertImageUrl(imageUrl);
        final name = categories[index].name;
        return GestureDetector(
          child: Stack(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: CachedNetworkImage(
                  fit: BoxFit.cover,
                  fadeInDuration: const Duration(milliseconds: 100),
                  fadeOutDuration: const Duration(seconds: 0),
                  imageUrl: imageUrl,
                ),
              ),
              Center(
                child: Text(
                  name,
                  style: TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.bold),
                ),
              )
            ],
          ),
          onTap: () {
            int id = categories[index].id;
            String imageUrl = categories[index].headerImage;
            String name = categories[index].description;
            Get.toNamed(Routes.VIDEO_CATEGORY, arguments: {"id": id, "headImageUrl": imageUrl, 'name': name});
          },
        );
      },
    );
  }
}
